import { createSlice } from "@reduxjs/toolkit"
import { getEtheraAccess, unlockEtheraAccess } from "../actions/getEtheraAccess"

interface AccessState {
  loading: boolean
  accessLocks: object[]
  error: string
}
const initialState: AccessState = {
  loading: false,
  accessLocks: [],
  error: "",
}

const AccessSlice = createSlice({
  name: "access",
  initialState,
  reducers: {
    resetAccess: (state) => {
      state.accessLocks = []
    },
  },
  extraReducers: (builder) => {
    //Reducer to get access Locks
    builder
      .addCase(getEtheraAccess.pending, (state, { payload }) => {
        state.loading = true
      })
      .addCase(getEtheraAccess.fulfilled, (state, { payload }) => {
        state.loading = false
        state.error = ""
        state.accessLocks = payload?.result
        console.log("getEtheraAccess successfull")
      })
      .addCase(getEtheraAccess.rejected, (state, { payload }) => {
        state.error = ""
        console.log("rejected in getEtheraAccess", payload)
      }),
      builder
        .addCase(unlockEtheraAccess.pending, (state, { payload }) => {
          state.loading = true
        })
        .addCase(unlockEtheraAccess.fulfilled, (state, { payload }) => {
          state.loading = false
          state.error = ""
          state.accessLocks = payload?.result
          console.log("unlockEtheraAccess successfull")
        })
        .addCase(unlockEtheraAccess.rejected, (state, { payload }) => {
          state.error = ""
          console.log("rejected in unlockEtheraAccess", payload)
        })
  },
})

export default AccessSlice.reducer
export const { resetAccess } = AccessSlice.actions
